package com.enzoism.springboot.dive.bis.pool;


import java.util.Random;
import java.util.concurrent.*;

public class CompletionTest {
    /**
     * 使用线程进行线程任务结果获取
     * 当前控制好corePoolsize，避免coolSize+LinkedBlockingDeque>MaxSize 就可以看到线层是如何取值的
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        Executor executor = new ThreadPoolExecutor(10, 60, 5000, TimeUnit.MICROSECONDS, new LinkedBlockingDeque<>(50));
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(executor);
        int taskNum = 40;
        for (int i = 0; i < taskNum; i++) {
            completionService.submit(new MyCallableTask());
        }
        // 等待线程完成
        for (int i = 0; i < taskNum; i++) {
            Integer integer = completionService.take().get();
            System.out.println("------->线程执行结果：" + integer);
        }
    }

    static class MyCallableTask implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            int num = new Random().nextInt(1000);
            System.out.println("------>" + Thread.currentThread().getName() + " 定时任务调度num:" + num);
            Thread.sleep(num);
            return num;
        }
    }
}
